using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UI;

[DefaultExecutionOrder(100)]
public class game : MonoBehaviour
{
    public Nodes node;
    public Dictionary<int, NodeVo> nodesDic = new Dictionary<int, NodeVo>();

    // 存储所有节点的 BoxCollider2D
    public List<BoxCollider2D> nodeColliders = new List<BoxCollider2D>();

    void Start()
    {
        foreach (var item in nodesDic.Values)
        {
            if (item.Type == 1)
            {
                createNode(item);
            }
        }
    }

    // Update is called once per frame
    void Update() { }

    // 创建节点的方法
    public void createNode(NodeVo nodeData)
    {
        // Debug.Log("创建");
        // 创建一个节点(预制体)
        Nodes newNode = Instantiate(node, this.transform);
        newNode.initData(nodeData);
    }

    // 根据节点id添加它的子节点
    public void addChildNode(Transform parentNode, int id)
    {
        // 根据id获取节点
        NodeVo nodeData = nodesDic[id];
        // 如果nodeData.ChildNode长度大于0,则添加子节点
        if (nodeData.ChildNode.Count > 0)
        {
            // 遍历来逐个添加nodeData.ChildNode
            foreach (var Id in nodeData.ChildNode)
            {
                // 如果已经存在则跳过
                if (!isNodeExist(Id) && Id > 0)
                {
                    if (nodesDic.ContainsKey(Id) && nodesDic[Id] != null)
                    {
                        Debug.Log("添加");
                        // 创建一个节点
                        Nodes newNode = Instantiate(node, this.transform);
                        newNode.initData(nodesDic[Id]);
                        // 为该节点绘制连线
                        Transform childNode = newNode.GetComponent<Transform>();
                        DrawConnectionLine(parentNode, childNode);
                    }
                }
            }
        }
    }

    // CheckOverlap 检查子节点nodes是否有重叠
    public void CheckOverlap()
    {
        // canvas
        Transform parentTransform = this.gameObject.transform;

        // nodes list
        List<Nodes> nodesList = new List<Nodes>();
        // 遍历所有的子物体
        foreach (Transform child in parentTransform)
        {
            // 获取子物体上 Nodes 组件
            Nodes node = child.GetComponent<Nodes>();
            nodesList.Add(node);
        }
        Debug.Log("nodesList");
        Debug.Log(nodesList);
        // foreach (Nodes node in nodesList)
        // {
        //     // 为每个节点动态添加 BoxCollider2D
        //     if (node.GetComponent<Collider2D>() == null) // 确保没有重复添加
        //     {
        //         BoxCollider2D collider = node.gameObject.AddComponent<BoxCollider2D>();
        //         collider.enabled = true;
        //         collider.isTrigger = false;
        //         Rigidbody2D rb = node.gameObject.AddComponent<Rigidbody2D>();
        //         // 设置物体为 kinematic
        //         rb.isKinematic = true; // 如果需要物体不受物理引擎控制，可以设置为 true
        //         // 设置是否受重力影响
        //         rb.gravityScale = 0; // 默认情况下物体会受到重力影响，设置为 0 就是禁用重力
        //         // 设置物理碰撞检测模式
        //         rb.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
        //         // 设置质量
        //         rb.mass = 0;
        //         // 从 RectTransform 获取尺寸
        //         RectTransform rectTransform = node.GetComponent<RectTransform>();
        //         // Debug.Log("rectTransform.rect.width");
        //         // Debug.Log(node);
        //         // Debug.Log(node.rectTransform);
        //         if (node.rectTransform != null)
        //         {
        //             collider.size = new Vector2(
        //                 node.rectTransform.rect.width,
        //                 node.rectTransform.rect.height
        //             );
        //             nodeColliders.Add(collider);
        //         }
        //     }
        // }
        // CheckOverlapAndMarkNodes();

        foreach (Nodes node in nodesList)
        {
            if (node != transform)
            {
                Transform nodeTrans = node.GetComponent<Transform>();
                // 使用 Physics2D.OverlapCircle 检查重叠
                Debug.Log("nodeTrans.position");
                Debug.Log(nodeTrans.position);
                Collider2D collider = Physics2D.OverlapCircle(nodeTrans.position, 0);
                Debug.Log("collider");
                Debug.Log(collider);
                if (collider != null && collider.gameObject != node.gameObject)
                {
                    Debug.Log($"{gameObject.name} 与 {collider.gameObject.name} 发生了重叠!");
                }
            }
        }
    }

    // 检查并记录重叠的节点
    private void CheckOverlapAndMarkNodes()
    {
        // 如果 nodeColliders 的 count 为0, 代码短路
        if (nodeColliders.Count < 1)
            return;
        // 清空记录的重叠节点
        List<BoxCollider2D> overlappedNodes = new List<BoxCollider2D>();

        // 遍历所有节点，检测与其他节点的重叠
        foreach (BoxCollider2D nodeCollider in nodeColliders)
        {
            // 跳过自身重叠
            if (nodeCollider.gameObject == gameObject)
                continue;

            // 检查当前节点与其他节点是否发生了重叠
            foreach (BoxCollider2D otherCollider in nodeColliders)
            {
                // 跳过自身检查
                if (nodeCollider == otherCollider)
                    continue;

                Debug.Log("nodeCollider.IsTouching(otherCollider)");
                Debug.Log(nodeCollider.IsTouching(otherCollider));

                // 检查是否重叠
                if (nodeCollider.IsTouching(otherCollider))
                {
                    // 确保只有没有记录过的重叠才会被添加
                    if (!overlappedNodes.Contains(nodeCollider))
                        overlappedNodes.Add(nodeCollider);
                    if (!overlappedNodes.Contains(otherCollider))
                        overlappedNodes.Add(otherCollider);
                }
            }
        }
        // 输出重叠的节点
        if (overlappedNodes.Count > 0)
        {
            Debug.Log("overlappedNodes");
            Debug.Log(overlappedNodes);
            Debug.Log("Found overlapping nodes:");
            foreach (BoxCollider2D overlappingNode in overlappedNodes)
            {
                Debug.Log(overlappingNode.gameObject.name);
            }
        }
    }

    private void DrawConnectionLine(Transform parentNodeTrans, Transform endNode)
    {
        // 创建连接线
        GameObject lineObject = new GameObject("LineConnector");
        LineConnector lineConnector = lineObject.AddComponent<LineConnector>();
        lineConnector.startNode = parentNodeTrans;
        lineConnector.endNode = endNode;
    }

    // 根据参数节点Id,判断当前节点是否已经添加到canvas
    public bool isNodeExist(int id)
    {
        Transform childTransform = transform.GetChild(0);
        if (childTransform != null)
        {
            // 找到子物体，进行进一步操作
            // 当前脚本组件绑定在canvas上面,创建预制体是创建在 canvas 物体内部
            // 所以需要获取 this.gameObject.transform => [Transform1, Transform2, Transform3]
            Transform parentTransform = this.gameObject.transform;
            List<int> currentIdList = new List<int>();
            // 遍历所有的子物体
            foreach (Transform child in parentTransform)
            {
                // 获取子物体上 Nodes 组件
                Nodes node = child.GetComponent<Nodes>();
                currentIdList.Add(node.nodeId);
            }
            // 判断id是否在currentIdList中
            if (currentIdList.Contains(id))
            {
                return true;
            }
        }
        else
        {
            // canvas下没有找到子物体
            Debug.LogError("ChildNode not found!");
            return true;
        }
        return false;
    }
}
